#!/usr/bin/env python

import xmpp, sys

"""
=====
GTalk
=====

``GTalk`` is a class which is able to translate some text using the Google Language Tools.
It requires the ``xmpp`` libray to talk to Google Translator using the ``jabber`` protocol.

"""

class GTalk ( object ):
	"""
	GTalk
	=====

	This is the GTalk class.
	"""
	def __init__ ( self ):
		self._client = None

	def connect ( self, login, password, name = 'gtalk-bot' ):
		self._client = xmpp.Client ( 'gmail.com', debug = [] )
		self._client.connect ( server = ( 'talk.google.com', 5223 ) )
		self._client.RegisterHandler ( 'message', self._msg_handler )
		self._client.auth ( login, password, name )
		self._client.sendInitPresence ()

	def _msg_handler ( self, conn, mess ):
		self._reply = mess.getBody ()

	def send ( self, txt, recipients, wait_reply = False ):
		if not isinstance ( recipients, list ):
			recipients = [ recipients ]
			
		if not self._client.isConnected (): 
			self._client.reconnectAndReauth ()

		for dest in recipients:
			msg = xmpp.Message ( dest, txt )
			msg.setType ( 'chat' )

			self._reply = None

			self._client.send ( msg )

		if  wait_reply:
			while not self._reply:
				self._client.Process ( 1 )

			return self._reply

		return True

if __name__ == '__main__':
	gt = GTalk ()
	login = raw_input ( "insert GTalk name: " )
	pwd   = raw_input ( "insert GTalk pwd:" )
	msg   = raw_input ( "Insert message: " )
	dest  = raw_input ( "Insert dest emails (space separated): " )
	gt.connect ( login, pwd )
	print gt.send ( msg, dest.split ( " " ) )



